/**
 * Created by leiweibo on 8/24/15.
 */
var app = angular.module('mecontroller', []);

app.controller('MeCtrl', function($scope, $window, MeService, Main) {
  if (!$window.sessionStorage.token) {
    window.location = "#/signin";
    return;
  }

  MeService.user_info(function(res) {
    if (res.result == true) {
      $scope.user = res.user;
    } else {
      $scope.error_msg = res.message;
    }
  });

  $scope.updateUserInfo = function() {
    var formData = $scope.user;
    formData.id = formData._id;
    Main.updateUser(formData, function (res) {
      if (res.result == true) {
        alert("用户信息更新成功，请推出重新登录");
        Main.logout(function (res) {
          if (res.result == true) {
            delete $window.sessionStorage.token;
            delete $window.sessionStorage.username
            delete $scope.token;
            delete $scope.username;
            window.location = "#/signin"
          } else {
            $scope.error_msg2 = res.message;
          }
        }), function () {
          alert("退出登录失败");
        };
      } else {
        $scope.error_msg = res.message;
      }
    }, function (data, status) {
      alert('服务器出错，请刷新重试!');
    })

  }

  $scope.updatePasswd = function() {
    var newPasswd = $scope.newpasswd;
    var newPasswd2 = $scope.renewpasswd;
    if (newPasswd !== (newPasswd2)) {
      alert("两次密码不一致, 请重试");
      return;
    }
    var data = {
      newPasswd: newPasswd,
      passwd: $scope.oldpasswd
    }

    MeService.update_passwd(data, function(res) {
      if (res.result == true) {
        alert("修改密码成功，请推出重新登录");
        Main.logout(function (res) {
          if (res.result == true) {
            delete $window.sessionStorage.token;
            delete $window.sessionStorage.username
            delete $scope.token;
            delete $scope.username;
            window.location = "#/signin"
          } else {
            $scope.error_msg2 = res.message;
          }
        }), function () {
          alert("退出登录失败");
        };
      } else {
        console.log(res.message);
        $scope.error_msg2 = res.message;
      }
    }, function(res) {
      $scope.error_msg2 = res.message;
    });
  }
});
